package com.tedu.egweibo.common.exception;


import com.tedu.egweibo.common.result.JsonResult;
import com.tedu.egweibo.common.result.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    // 捕获异常
    @ExceptionHandler
    public JsonResult doHandleRuntimeException(RuntimeException e) {
        //
        log.info("处理RuntimeException!!!");
        log.error(e.getMessage(),e);
        return new JsonResult(StatusCode.OPERATION_FAILED);
    }

    // 处理参数校验异常 Validation
    // 处理封装参数异常 MethodArgumentNotValidException
    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.info("处理MethodArgumentNotValidException!!!");
        // 获取第一个错误信息
        String message = e.getFieldError().getDefaultMessage();
        log.error(message,e);
        return new JsonResult(StatusCode.VALIDATE_ERROR,message);
    }
    // 处理参数校验异常 ConstraintViolationException
    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException e) {
        log.info("处理ConstraintViolationException!!!");
        // 获取第一个错误信息
        String message = e.getMessage();
        message=message.substring(message.indexOf(":")+1).trim();
        log.error(message,e);
        return new JsonResult(StatusCode.VALIDATE_ERROR,message);
    }


    //处理未知异常
    @ExceptionHandler
    public JsonResult doHandeleThrowable(Throwable e) {
        log.info("处理Throwable!!!");
        log.error(e.getMessage(),e);
        return new JsonResult(StatusCode.UNKNOWN_ERROR);
    }



}
